import {LoginService} from '../../view/login/loginService';
import {Msg} from '../../tools/message';
import {Auth} from './auth';
import {mymessage} from "../../tools/mymessage";
import {postRequest} from "../../tools/api";
import da from "element-ui/src/locale/lang/da";

const defaultUser = {login: '', password: '', remember: false};

export default {
  state: {
    /** token */
    // token: Auth.getToken() || null,
    /** 用户登陆角色信息 */
    userInfo: Auth.getUserInfo() || {},
    /** 用户登陆账户密码 */
    accountPwd: Auth.getAccountPwd() || defaultUser,
    /** 是否登陆 */
    isLogin: Auth.getLogin() || false,
    courseId: Auth.getCurrentCourseId() || {},
    taskId: Auth.getCurrentTaskId() || {}
  },
  /** 计算属性 */
  getters: {},
  /** 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation */
  mutations: {
    ACCOUNT_AUTH_STATUS_CHANGED(state, data) {
      // console.log("data", data);
      const d = data.data;
      // if (data.params.remember) {
      //   state.accountPwd = data.params;
      //   Auth.setAccountPwd(data.params)
      // }
      // console.log('当前登录角色信息：', d);
      state.userInfo = d;

      state.isLogin = true;
      Auth.setUserInfo(d);
      Auth.setLogin();
    },
    ACCOUNT_LOGOUT_FAILURE(state) {
      state.token = null;
      state.userInfo = {};
      state.accountPwd = {};
      state.permission = [];
      state.isLogin = false;
      state.myCourse = [];
      state.currentCourse = {};
      state.myTask = {};
      Auth.removeToken();
      Auth.removeUserInfo();
      Auth.removeAccountPwd();
      Auth.removeLogin();
      /*      Auth.removeMyCourse();
            Auth.removeCurrentCourse();
            Auth.removeMyTask();*/
    },
    ACCOUNT_LOGOUT_ROULES(state) {
      state.permission = Auth.getUserInfo().permissionKeys
    },
    SAVA_CURRENT_COURSE_ID(state, data) {
      state.courseId = data
      Auth.setCurrentCourseId(data)
    },
    SAVA_CURRENT_TASK_ID(stata, data) {
      stata.taskId = data
      Auth.setCurrentTaskId(data)
    }
  },
  /** Action 提交的是 mutation，而不是直接变更状态。Action 可以包含任意异步操作。 */
  actions: {
    /** 登录 */
    submitLogin({commit}, params) {
      return new Promise(((resolve, reject) => {
        postRequest('/user/login', params).then(resp => {
          // console.log("resp: ", resp);
          if (resp.code === 200) {
            commit('ACCOUNT_AUTH_STATUS_CHANGED', {...resp, params})
            mymessage.success('登录成功');
            resolve(resp);
          } else {
            sessionStorage.setItem('isLogin', false);
            mymessage.warning('账号或密码错误,请重新输入');
            reject('账号或密码错误,请重新输入')
          }
        }).catch(err => {
          reject(err);
          commit('ACCOUNT_LOGOUT_FAILURE');
        })
      }))
    },
    /** 注册 */
    submitRegister({commit}, params) {
      return new Promise(((resolve, reject) => {
        postRequest('user/register', params).then(resp => {
          console.log(resp);
          if (resp.code === 200) {
            mymessage.success('注册成功');
            resolve(resp);
          } else {
            mymessage.warning('账号或密码错误,请重新输入');
            reject('账号或密码错误,请重新输入')
          }
        }).catch(err => {
          reject(err);
          commit('ACCOUNT_LOGOUT_FAILURE');
        })
      }))
    },
    submitEditBaseInfo({commit}, params) {
      return new Promise(((resolve, reject) => {
        postRequest('/user/updateBaseInfo', params).then(resp => {
          if (resp.code === 200) {
            commit('ACCOUNT_AUTH_STATUS_CHANGED', {...resp, params})
            mymessage.success('修改信息成功');
            resolve(resp);
          } else {
            mymessage.warning('修改信息失败');
            reject('修改信息失败')
          }
        }).catch(err => {
          reject(err);
          commit('ACCOUNT_LOGOUT_FAILURE');
        })
      }))
    },
    submitSettingInfo({commit}, params) {
      return new Promise(((resolve, reject) => {
        postRequest('/user/updateSettingInfo', params).then(resp => {
          console.log("resp", resp);
          if (resp.code === 200) {
            commit('ACCOUNT_AUTH_STATUS_CHANGED', {...resp, params})
            mymessage.success('修改信息成功');
            resolve(resp);
          } else {
            mymessage.warning('修改信息失败');
            reject('修改信息失败')
          }
        }).catch(err => {
          reject(err);
          commit('ACCOUNT_LOGOUT_FAILURE');
        })
      }))
    },
    /** 登出 */
    accountLogoutSubmit({commit}) {
      commit('ACCOUNT_LOGOUT_FAILURE');
    },
    /** 赋值角色权限 */
    accountSetRoules({commit}) {
      return new Promise(resolve => {
        commit('ACCOUNT_LOGOUT_ROULES');
        resolve()
      })
    },
    /**
     * 老师通过id获取自己的课程
     * @param commit
     * @param teacherId
     * @returns {Promise<unknown>}
     */
    /*    getCourseByTeacherId({commit}, teacherId) {
          return new Promise( resolve => {
            console.log(teacherId);
            teacherClassListService.findCourseByTeacherId(teacherId).then((result) => {
              console.log(result);
              commit('ACCOUNT_AUTH_STATUS_CHANGED_OF_MY_COURSE', result);
              resolve();
            });
          })
        },*/
    /*    getCourseByStudentId({commit}, studentId) {
          return new Promise( resolve => {
            studentClassListService.findCourseByStudentId(studentId).then((result) => {
              commit('ACCOUNT_AUTH_STATUS_CHANGED_OF_MY_COURSE', result);
              resolve();
            });
          })
        },*/
    saveCurrentCourse({commit}, currentCourse) {
      return new Promise(resolve => {
        commit('SAVA_CURRENT_COURSE', currentCourse);
        resolve();
      })
    },
    /*    findTaskByTaskGroup({commit}, taskGroup) {
          return new Promise(resolve => {
            teacherClassService.findTaskByTaskGroup(taskGroup).then((result) => {
              commit('SAVE_TASK', result);
              resolve();
            })
          })
        },*/
    /*    findTaskByTeacherId({commit}, teacherId) {
          return new Promise(resolve => {
            teacherClassService.findTaskByTeacherId(teacherId).then((result) => {
              // console.log(result.data.get("10"));
              commit('SAVE_TASK', result);
              resolve();
            })
          })
        }*/
  }
}
